package io.aicn.lowcode.controller.dbmanager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.aicn.lowcode.entity.dbmanager.DataTable;
import io.aicn.lowcode.service.dbmanager.IDataTableService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据表管理Controller
 * 
 * @author lowcode-generator
 * @since 2025-01-25
 */
@Slf4j
@RestController
@RequestMapping("/api/dbmanager/datatable")
@Tag(name = "数据表管理", description = "数据表信息的查询和管理")
public class DataTableController {

    @Autowired
    private IDataTableService dataTableService;

    @Operation(summary = "分页查询数据表列表")
    @GetMapping("/page")
    public ResponseEntity<Map<String, Object>> page(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "数据源ID") @RequestParam(required = false) Long dataSourceId,
            @Parameter(description = "表名") @RequestParam(required = false) String tableName,
            @Parameter(description = "表注释") @RequestParam(required = false) String tableComment) {
        
        Page<DataTable> page = new Page<>(current, size);
        QueryWrapper<DataTable> queryWrapper = new QueryWrapper<>();
        
        if (dataSourceId != null) {
            queryWrapper.eq("datasource_id", dataSourceId);
        }
        if (tableName != null && !tableName.trim().isEmpty()) {
            queryWrapper.like("table_name", tableName.trim());
        }
        if (tableComment != null && !tableComment.trim().isEmpty()) {
            queryWrapper.like("table_comment", tableComment.trim());
        }
        
        queryWrapper.orderByDesc("update_time");
        
        Page<DataTable> result = dataTableService.page(page, queryWrapper);
        
        Map<String, Object> response = new HashMap<>();
        response.put("records", result.getRecords());
        response.put("total", result.getTotal());
        response.put("current", result.getCurrent());
        response.put("size", result.getSize());
        response.put("pages", result.getPages());
        
        return ResponseEntity.ok(response);
    }

    @Operation(summary = "根据数据源ID查询表列表")
    @GetMapping("/list/{dataSourceId}")
    public ResponseEntity<List<DataTable>> listByDataSourceId(
            @Parameter(description = "数据源ID") @PathVariable Long dataSourceId) {
        
        List<DataTable> list = dataTableService.listByDataSourceId(dataSourceId);
        return ResponseEntity.ok(list);
    }

    @Operation(summary = "根据ID查询数据表详情")
    @GetMapping("/{id}")
    public ResponseEntity<DataTable> getById(@Parameter(description = "数据表ID") @PathVariable Long id) {
        DataTable dataTable = dataTableService.getById(id);
        if (dataTable == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(dataTable);
    }

    @Operation(summary = "同步表结构信息")
    @PostMapping("/{tableId}/sync")
    public ResponseEntity<Map<String, Object>> syncTableStructure(
            @Parameter(description = "表ID") @PathVariable Long tableId) {
        try {
            boolean result = dataTableService.syncTableStructure(tableId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", result);
            response.put("message", result ? "同步成功" : "同步失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("同步表结构失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "同步失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @Operation(summary = "刷新数据表统计信息")
    @PostMapping("/refresh-stats/{id}")
    public ResponseEntity<Map<String, Object>> refreshTableStats(
            @Parameter(description = "数据表ID") @PathVariable Long id) {
        try {
            boolean result = dataTableService.refreshTableStats(id);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", result);
            response.put("message", result ? "刷新成功" : "刷新失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("刷新表统计信息失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "刷新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @Operation(summary = "批量刷新数据源下所有表的统计信息")
    @PostMapping("/refresh-all-stats/{dataSourceId}")
    public ResponseEntity<Map<String, Object>> refreshAllTableStats(
            @Parameter(description = "数据源ID") @PathVariable Long dataSourceId) {
        try {
            List<DataTable> tables = dataTableService.listByDataSourceId(dataSourceId);
            int successCount = 0;
            int failCount = 0;
            
            for (DataTable table : tables) {
                try {
                    boolean success = dataTableService.refreshTableStats(table.getId());
                    if (success) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    log.warn("刷新表 {} 统计信息失败: {}", table.getTableName(), e.getMessage());
                    failCount++;
                }
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", String.format("批量刷新完成，成功: %d，失败: %d", successCount, failCount));
            response.put("successCount", successCount);
            response.put("failCount", failCount);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("批量刷新表统计信息失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "批量刷新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @Operation(summary = "删除数据表记录")
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> delete(@Parameter(description = "数据表ID") @PathVariable Long id) {
        try {
            boolean success = dataTableService.removeById(id);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "删除成功" : "删除失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除数据表记录失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @Operation(summary = "批量删除数据源下的所有表记录")
    @DeleteMapping("/batch/{dataSourceId}")
    public ResponseEntity<Map<String, Object>> batchDeleteByDataSourceId(
            @Parameter(description = "数据源ID") @PathVariable Long dataSourceId) {
        try {
            QueryWrapper<DataTable> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("data_source_id", dataSourceId);
            
            boolean success = dataTableService.remove(queryWrapper);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "批量删除成功" : "批量删除失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("批量删除数据表记录失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "批量删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}